/**
 * @author selkhateeb
 */

dojo.provide("nanosn.tracfaces.ui.ResourceDataEditor");

dojo.require("nanosn.tracfaces.ui.DataEditor");
dojo.require("dojox.dtl");
dojo.require("dojox.dtl.Context");
dojo.require("dijit.layout.ContentPane");

dojo.declare("nanosn.tracfaces.ui.ResourceDataEditor",
    /* Extends */ nanosn.tracfaces.ui.DataEditor,
    {

        /**
         * Holds the structure of the subgrid
         */
        subGridStructure: null,

        /**
         * a DTL template contains a url template that points at the database.
         * this url MUST contain:
         *   - parentRowId - a place holder for the parent row id
         *                   this id will be replaced by the actual parent id
         *                   which is theortically is the foriegn key for the
         *                   sub grid rows when doing the SQL query on the
         *                   server.
         *
         *                   Examples:
         *                     subGridUrl: "resource?parentid={{ parentRowId }}"
         */
        subGridUrl: null,

        /**
        * Constructor
        * @param {Object} args :
        *          subGridStructure: the layout of the subgrid.
        *          subGridUrl      : the url of the data source for the subgrid.
        *              		      the url should be some how generated
        *              		      dynamically inside this class,
        *              		TODO: how should the data look like in the URL.
        */
        constructor: function(args)
        {
            console.debug("constructor");
		
            dojo.mixin(this, args);

            this.subGridStructure = this.structure.slice(0);
            this._createStructure(this._grid.structure);

            //TODO: if(testMode)
            //this._initilizeDummyData();
            //end of testMode
            
            this._initilizeWidgets();
            this._createEditorView();

        },

        /**
        * initilizes the widgets
        */
        _initilizeWidgets: function()
        {
            console.log("_initilizeWidgets");
            console.log(this);

            /***********
         * Subscribing functions to be used with events
         * and fixes the scope.
         ***********/
            dojo.subscribe("this._onBeforeRow", this, this._onBeforeRow);
            dojo.subscribe("this._buildSubgrid", this, this._buildSubgrid);
            dojo.subscribe("this.toggleDetail", this, this.toggleDetail);

            dojo.subscribe("this._getDetail", this, this._getDetail);
        },

        /**
         * TODO: Destroy function
         */
        _destroy: function()
        {
        //TODO: unsubscribe

        },
    
        /**
        * Resets rhe structure of the parent grid where it addes
        * the +/- and the subgrid columns
        * @param {Object} structure: original structure of th parent grid.
        */
        _createStructure: function(structure)
        {
            console.log("_createStructure - Structure as it comes:");
            console.log(structure);
        
            //event handling: onBeforeRow
            var _obr = function(inDataIndex, inSubRows)
            {
                params = [inDataIndex, inSubRows]
                dojo.publish("this._onBeforeRow", params);
            };
        
            //The +/- column
            var _check =
            {
                name: '',
                width: 3,
                get: dojo.hitch(this, "_getCheck"),
                styles: 'text-align: center;'
            };
        
            //Insert the check(+/_) column to the beginning of the layout
            structure.unshift(_check);
        
            //The sub grid place holder
            var _gridPlaceHolder =
            {
                name: '',
                get: function(inRowIndex)
                {
                    cell = this;
                    dojo.publish("this._getDetail", [inRowIndex, cell]);
                    // insert a placeholder
                    return '<div style="height: ' + 12
                    + 'px; background-color: white;"></div>';
                //return dojo.hitch(this, "__getDetail");
                },
                colSpan: structure.length,
                styles: 'padding: 0; margin: 0;'
            };
        
            //put it all together to make the new grid layout
            var gridCells = [
            {
                onBeforeRow: _obr,
                cells: [structure, [_gridPlaceHolder]]
            }];
        
            //Reset the main grid layout with the one we just created.
            this._grid.setStructure(gridCells);
        },
 

        /**
       * Generates a unique id for the subgrid to be identified.
       * @param {Object} inRowIndex parent grid index row
       */
        _makeSubgridId: function(inRowIndex)
        {
            console.log("_makeSubgridId");
            console.log(this);
            return this._grid.widgetId + "_subGrid_" + inRowIndex;
        },
    
        /**
        * if a subgrid exists at inRowIndex, detach it from the DOM
        * @param {Object} inRowIndex
        */
        _detachSubgrid: function(inRowIndex)
        {
            console.log("_detachSubgrid");
            console.log(this);
            var subGrid = dijit.byId(this._makeSubgridId(inRowIndex));
            if (subGrid)
                dojox.grid.util.removeNode(subGrid.domNode);
        },
    
        /**
        * render a subgrid into inCell at inRowIndex
        * @param {Object} inRowIndex
        * @param {Object} inCell
        */
        _buildSubgrid: function(inRowIndex, inCell)
        {
            

            console.log("_buildSubgrid");
            console.log(this);
            console.log(inCell);
            var n = inCell.getNode(inRowIndex).firstChild;
            console.log(n);
        
            var id = this._makeSubgridId(inRowIndex);
        
            var subGrid = dijit.byId(id);
            if (subGrid)
            {
                n.appendChild(subGrid.domNode);
                subGrid.render();
            }
            else
            {
                dojox.grid.DataGrid.get
                console.log("this._grid.get(inRowIndex)");
                console.log((this._grid.getItem(inRowIndex)).i.id);
                var template = new dojox.dtl.Template(this.subGridUrl);
                var context = new dojox.dtl.Context(
                {
                    parentRowId: (this._grid.getItem(inRowIndex)).i.id //TODO this is not the real id
                });
                console.debug(template.render(context));
                
                _store = new dojox.data.QueryReadStore({
                    url:template.render(context)
                });
                _subGridProps =
                {
                    structure: this.subGridStructure,
                    autoHeight: true,
                    autoRender: false,
                    query:
                    {
                        id: '*'
                    },
                    
                    store: _store
            
                }
                _subGridProps.dataRow = inRowIndex;
                _subGridProps.widgetId = id;
                subGrid = new dojox.grid.DataGrid(_subGridProps, n);
                subGrid.startup();
            }
        
            //Adjust row height
            if (subGrid)
            {
                subGrid.cacheHeight = subGrid.domNode.offsetHeight;
                inCell.grid.rowHeightChanged(inRowIndex);
            }
        
        },
   
        /**
        * destroy subgrid at inRowIndex
        * @param {Object} inRowIndex
        */
        _destroySubgrid: function(inRowIndex)
        {
    
            console.log("_destroySubgrid");
            console.log(this);
            var subGrid = dijit.byId(this._makeSubgridId(inRowIndex));
            if (subGrid)
                subGrid.destroy();
        },

        /**
         * A place holder to hold the state of visible rows.
         */
        _detailRows: [],

        /**
        * when user clicks the +/-
        * @param {Object} inIndex
        * @param {Object} inShow
        */
        toggleDetail: function(inIndex, inShow)
        {
            console.log("toggleDetail");
            console.log(this);
            if (!inShow)
                this._detachSubgrid(inIndex);
            this._detailRows[inIndex] = inShow;
            this._grid.updateRow(inIndex);
        },
    
        /**
        * html for the +/- cell
        * @param {Object} inRowIndex
        */
        _getCheck: function(inRowIndex)
        {
            console.debug("_getCheck");
            
            image = (this._detailRows[inRowIndex] ? 
                dojo.moduleUrl("nanosn.tracfaces.ui",'images/open.gif')
                :
                dojo.moduleUrl("nanosn.tracfaces.ui",'images/closed.gif'));
            show = (this._detailRows[inRowIndex] ? 'false' : 'true')

            return '<img height="11" width="11" src="' + image
            + '" onclick="dojo.publish(\'this.toggleDetail\',['
            + inRowIndex + ',' + show + ']);">';
        },
    
    
        /**
        * onBeforeRow event
        * @param {Integer} inDataIndex
        * @param {Object} inSubRows
        */
        _onBeforeRow: function(inDataIndex, inSubRows)
        {
    
            console.log("_onBeforeRow");
            console.log(this);
            inSubRows[1].hidden = !this._detailRows[inDataIndex];
        },


        /**
         * Initilizes dummy data for testing purposes.
         */
        _initilizeDummyData: function()
        {
            // Set the sub grid structure
            this.subGridStructure = [
            {
                noscroll: true,
                cells: [[
                {
                    name: "id",
                    field: "id",
                    rowSpan: 2,
                    width: 10,
                    noresize: true,
                    styles: 'text-align:center;'
                },
                {
                    name: "Sku",
                    field: "sku"
                },
                {
                    name: "Price",
                    field: "price"
                },
                {
                    name: "Vendor",
                    field: "vendor"
                },
                {
                    name: "Name",
                    width: "auto",
                    field: "name"
                }], [
                {
                    name: "Description",
                    field: "desc",
                    colSpan: 4
                }]]
            }];
        
            // Create dummy data
            var data12 =
            {
                identifier: 'id',
                label: 'id',
            
                items: [
            
                {
                    id: '1',
                    sku: '23423432423',
                    price: '$10.00',
                    vendor: 'Sobeys',
                    name: "Chocolate",
                    desc: "Nice Chocolate Bar"
                },
                {
                    id: '2',
                    sku: '23423432423',
                    price: '$20.00',
                    vendor: 'Sobeys',
                    name: "2 Chocolate",
                    desc: "2 Nice Chocolate Bar"
                },
                {
                    id: '3',
                    sku: '3323423432423',
                    price: '$310.00',
                    vendor: 'Sobeys',
                    name: "3 Chocolate",
                    desc: "Sweet and Nice Chocolate Bar"
                }, ]
            };

            // Set the sub grid data
            this._subGridDataStore = new dojo.data.ItemFileReadStore(
            {
                data: data12
            });
        
        },
    

        /**
        * Calls this._buildSubgrid() function after a time out
        * @param {Object} inRowIndex
        * @param {Object} cell
        */
        _getDetail: function(inRowIndex, cell)
        {
            console.log("__getDetail");
            console.log(this);
            console.log(cell);
        
            // we can affect styles and content here, but we have to wait
            // to access actual nodes.
            setTimeout(function()
            {
                dojo.publish("this._buildSubgrid", [inRowIndex, cell]);
            }, 1);
		
        /* TODO: See if it is possible to disable the onmouseover event
		 *       where it goes all blue.
		 */

        },

        /**********************************************************
         * Editor View
         **********************************************************/
        _createEditorView: function()
        {
            /***********
             * Booking Editor
             ***********/
            bookingPane = new dijit.layout.ContentPane(
            {
                id: "bookingPane",
                title: "bookingPane",
                style:"height: 300px; width:500px",
                content: div
            });
            div = document.createElement("div");
            div.innerHTML = "WOOW";
            //div.style = "height: 300px; width:500px";
            
            bookingEditor = new nanosn.tracfaces.ui.DataEditor(
            {
                structure: [
                {
                    field: "id",
                    name: "ID",
                    width: '25px'
                },
                {
                    field: "name",
                    name: "a",
                    width: "150px"
                },
                {
                    field: "efficincy",
                    name: "b",
                    width: "100px"
                },
                {
                    field: "flags",
                    name: "Flags",
                    width: "100px"
                },
                {
                    field: "rate",
                    name: "c",
                    width: "100px"
                },
                {
                    field: "vacation",
                    name: "d",
                    width: "100px"
                }
                ],
                url:"?data=resource"
                
            }, bookingPane.domNode);
            
            dojo.body().appendChild(bookingPane.domNode);
            //this._contentPaneEditor.attr('content', bookingPane.domNode);
            
            
            
        }
    });
